module rx_data(
    input   wire            sys_clk ,
    input   wire            reset_n ,
    input   wire            uart_rx ,

    output  reg     [3:0]   real_id ,      // 读取的ID
    output  reg     [11:0]  real_data ,    // 读取的数值
    output  reg             real_flag      // 读取完毕
);

// 寄存
wire [7:0]  data_byte_rx    ;
wire        rx_done         ;

reg  [3:0]  data_reg        ;
reg  [11:0] fre_reg         ;

uart_byte_rx uart_byte_rx_inst
(
	.clk         (sys_clk   ),
	.reset_n     (reset_n   ),
	.baud_set    (3'd4      ),
	.uart_rx     (uart_rx   ), //
	.data_byte   (data_byte_rx),
	.rx_done     (rx_done   )
);

reg uart_data_start;
reg [3:0] index_data; // 发送数据个数 1

always @(posedge sys_clk or negedge reset_n) begin
    if(!reset_n) begin
        uart_data_start <= 1'b0;
    end else if(data_byte_rx == 8'h23) begin // #作为开头
        uart_data_start <= 1'b1;
    end else if(data_byte_rx == 8'h21) begin // !作为结尾
        uart_data_start <= 1'b0;
    end else begin
        uart_data_start <= uart_data_start ;
    end
end

// index_data
always@(posedge sys_clk or negedge reset_n)
begin
    if(!reset_n) begin
        index_data <= 1'b0;
    end else if(rx_done && uart_data_start) begin
        index_data <= index_data + 1'b1 ;
    end else if(rx_done && !uart_data_start) begin
        index_data <= 1'b0 ;
    end else
        index_data <= index_data ;
end

// data_reg
always@(posedge sys_clk or negedge reset_n) begin
    if(!reset_n) begin
        data_reg <= 1'b0;
    end else if(uart_data_start && rx_done) begin
        case (index_data)  //
            4'd2: data_reg <= data_byte_rx[3:0];
            default : data_reg <= data_reg;
        endcase
    end else begin
        data_reg <= data_reg;
    end
end

// fre_data
always@(posedge sys_clk or negedge reset_n) begin
    if(!reset_n) begin
        fre_reg <= 1'b0;
    end else if(uart_data_start && rx_done) begin
        case (index_data)  //
            4'd3: fre_reg <= 1'b0;
            4'd4: fre_reg <= fre_reg + data_byte_rx[3:0] * 10'd1000;
            4'd5: fre_reg <= fre_reg + data_byte_rx[3:0] *   7'd100;
            4'd6: fre_reg <= fre_reg + data_byte_rx[3:0] *    4'd10;
            4'd7: fre_reg <= fre_reg + data_byte_rx[3:0];
            default : fre_reg <= fre_reg;
         endcase
    end else begin
        fre_reg <= fre_reg;
    end
end

always@(posedge sys_clk or negedge reset_n) begin
    if(!reset_n) begin
        real_flag <= 1'b0;
        real_data <= 1'b0;
        real_id   <= 1'b0;
    end else if(rx_done && (data_byte_rx == 8'h21)) begin
        real_data <= fre_reg;
        real_id   <= data_reg;
        real_flag <= 1'b1;
    end else begin
        real_flag <= 1'b0;
        real_data <= real_data;
        real_id   <= real_id ;
    end
end

endmodule